package com.iteaj.iot.client.websocket;

import com.iteaj.iot.AbstractProtocol;
import com.iteaj.iot.SocketMessage;
import com.iteaj.iot.client.ClientConnectProperties;
import com.iteaj.iot.client.IotClient;
import com.iteaj.iot.client.MultiClientManager;
import com.iteaj.iot.client.TcpSocketClient;
import com.iteaj.iot.client.codec.WebSocketClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.List;

public class DefaultWebSocketClientComponent extends WebSocketClientComponentAbstract<DefaultWebSocketClientMessage> {

    private List<WebSocketClientListener> listeners;

    public DefaultWebSocketClientComponent() { }

    public DefaultWebSocketClientComponent(MultiClientManager clientManager) {
        super(null, clientManager);
    }

    @Override
    public TcpSocketClient createNewClient(ClientConnectProperties config) {
        return new WebSocketClient(this, (WebSocketClientConnectProperties) config);
    }

    @Override
    public String getName() {
        return "websocket(Client)";
    }

    @Override
    public String getDesc() {
        return "WebSocket客户端默认实现";
    }

    @Override
    public WebSocketClientConnectProperties getConfig() {
        return (WebSocketClientConnectProperties) super.getConfig();
    }

    @Override
    public SocketMessage createMessage(byte[] message) {
        return new DefaultWebSocketClientMessage(message);
    }

    @Override
    public AbstractProtocol getProtocol(DefaultWebSocketClientMessage message) {
        return new DefaultWebSocketClientProtocol(message);
    }

    @Override
    public void connect() {
        super.connect();
        if(!CollectionUtils.isEmpty(this.listeners)) {
            // 连接所有需要监听的客户端
            this.listeners.forEach(item -> {
                WebSocketClientConnectProperties properties = item.properties();
                IotClient client = getClient(properties);
                if(client != null) {
                    return;
                }

                // 绑定对应的连接
                properties.setListener(item);
                createNewClientAndConnect(properties);
            });
        }
    }

    public List<WebSocketClientListener> getListeners() {
        return listeners;
    }

    @Autowired
    public void setListeners(List<WebSocketClientListener> listeners) {
        this.listeners = listeners;
    }

}
